/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bm.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 *
 * @author naseh it6
 */
public final class PropertiesLoader {

    private static Properties properties;
    private final Map<String, String> map = new HashMap<String, String>();
    private FileInputStream fileinputStream;
    private String path;

    public PropertiesLoader(String fileName) throws IOException {
        reloadProperties(fileName);
    }

    public void reloadProperties(String fileName) throws IOException {
        try {
            properties = new Properties();
            path = getJarFolder();
            fileinputStream = new FileInputStream(path + fileName);
            properties.load(fileinputStream);
            fileinputStream.close();
            for (String key : properties.stringPropertyNames()) {
                String value = properties.getProperty(key);
                map.put(key, value);
            }
        } catch (FileNotFoundException ex) {
            System.out.println("File Properties tidak ditemukan " + ex);
        }
    }

    public Map<String, String> getProperties() {
        return map;
    }

    private String getJarFolder() {
        try {
            String jarPath = PropertiesLoader.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            String decodedPath = URLDecoder.decode(jarPath, "UTF-8");
            decodedPath = decodedPath.replace('/', File.separatorChar);
            if (decodedPath.contains(".jar")) {
                decodedPath = decodedPath.substring(0, decodedPath.indexOf(".jar") + 4);
                decodedPath = decodedPath.substring(0, decodedPath.lastIndexOf(File.separatorChar) + 1);
            }
            return decodedPath;
        } catch (UnsupportedEncodingException ex) {
            System.out.println("Error Encoding path folder for properties file" + ex);
        }
        return null;
    }

}
